package com.study.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.github.pagehelper.PageInfo;
import com.study.model.User;
import com.study.model.UserList;
import com.study.model.UserPoi;
import com.study.model.UserRole;
import com.study.service.UserRoleService;
import com.study.service.UserService;
import com.study.util.PasswordHelper;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kh
 * @time 2021.9.2
 */
@RestController
@RequestMapping("/users")
public class UserController {
    @Resource //@Autowire
    private UserService userService;
    @Resource
    private UserRoleService userRoleService;

    /**
     * 用户列表
     * @param user 组合查询条件
     * @param draw 数据
     * @param start 分页开始
     * @param length 每页的数据大小
     * @return
     */
//    @RequestMapping
//    public Map<String, Object> getAll(User user, String draw,
//                                      @RequestParam(required = false, defaultValue = "1") int start,
//                                      @RequestParam(required = false, defaultValue = "10") int length) {
//        Map<String, Object> map = new HashMap<>();
//        PageInfo<User> pageInfo = userService.selectByPage(user, start, length);
////        System.out.println("pageInfo.getTotal():" + pageInfo.getTotal());
//        map.put("draw", draw);
//        map.put("recordsTotal", pageInfo.getTotal());
//        map.put("recordsFiltered", pageInfo.getTotal());
//        map.put("data", pageInfo.getList());
//        return map;
//    }


    @RequestMapping(value = "userList")
    public Map<String, Object> queryUser(User user, String draw,
                                      @RequestParam(required = false, defaultValue = "1") int start,
                                      @RequestParam(required = false, defaultValue = "10") int length) {
        Map<String, Object> map = new HashMap<>();
        PageInfo<UserList> pageInfo = userService.queryAllUserInfo(user, start, length);
        System.out.println("pageInfo.getTotal():" + pageInfo.getTotal());
        map.put("draw", draw);
        map.put("recordsTotal", pageInfo.getTotal());
        map.put("recordsFiltered", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        return map;
    }


    /**
     * 保存用户角色
     *
     * @param userRole 用户角色
     *                 此处获取的参数的角色id是以 “,” 分隔的字符串
     * @return
     */
    @RequestMapping("/saveUserRoles")
    public String saveUserRoles(UserRole userRole) {
        if (StringUtils.isEmpty(userRole.getUserid()))
            return "error";
        try {
            userRoleService.addUserRole(userRole);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @RequestMapping(value = "/add")
    public String add(User user) {
        //判断是否存在用户
        User u = userService.selectByUsername(user.getUsername());
        if (u != null)
            return "error";
        try {
            user.setEnable(1);
            PasswordHelper passwordHelper = new PasswordHelper();
            passwordHelper.encryptPassword(user);
            userService.save(user);
            Integer userId = userService.getUserId(user.getUsername()); //获取到插入的用户id
            userService.setUserRole(userId);//新增用户默认设置为普通用户
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }

    /**
     * 删除用户
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete")
    public String delete(String ids) {
        String[] a = ids.split(",");
        int array[] = new int[a.length];
        for(int i=0;i<a.length;i++) {
            array[i] = Integer.parseInt(a[i]);
        }
        try {
            userService.delUser(array);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }

    /**
     * 获取到用户的信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/detail")
    public User detail(Integer id) {
        User user = userService.detailUser(id);
       System.out.println("用户的详情：" + user.getUsername() + "状态：" + user.getEnable());
        return user;
    }

    /**
     * 启用用户
     */
    @RequestMapping(value = "/enable")
    public int enable(Integer id) {
        if (userService.queryUserStatus(id)==1){
            return 1;
        }
        return userService.enableUserById(id);
    }

    /**
     * 禁用用户
     */
    @RequestMapping(value = "/disable")
    public int disable(Integer id) {
        if (userService.queryUserStatus(id)==0){
            return 0;
        }
        return userService.disableUserById(id);
    }

    @RequestMapping(value = "/exportUser")
    public String exportUserList() throws IOException {
        List<UserPoi> userList = userService.exportUserList();//获取到导出的数据
        for (UserPoi users:userList){


        }
        //设置Excel的描述文件
        ExportParams exportParams = new ExportParams("用户列表的所有数据", "用户信息" , ExcelType.XSSF);
        //进行导出的基本操作
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, UserPoi.class, userList);
        //输入输出流地址
        FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\users.csv");
        //进行输出流
        workbook.write(fileOutputStream);
        //关流
        fileOutputStream.close();
        workbook.close();
        System.out.println(userList.size() + "长度");
        if (userList!=null){
            return "success";
        }
        else {
            return "fail";
        }

    }

//    /**
//     * 获取操作用户的状态
//     * @param id 用户id
//     * @return
//     */
//    @RequestMapping(value = "userStatus")
//    public int userStatus(Integer id){
//        return userService.queryUserStatus(id);
//    }
}
